#!/bin/bash
##############################################
# 维护消息队列，更新配置文件中的日期，启动程序

# 替换 my_config.ini 的第三行为 target_time_all = 2019:08:01:14:30:00

# 如果当前环境未安装 libpcap，请执行以下命令创建软连接，并将动态库所在目录加入到环境变量。
#ln-s libpcap.so.1.5.3  libpcap.so.1
#export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH

# 从网卡抓数据需要root权限，加sudo
#sudo /tmp/tmp.FdUHWCPhyb/bin/Network_Traffic_Processing
##############################################
curr_dir=$(pwd)
#work_dir="/home/app/Network_Traffic_Processing/"
work_dir=${curr_dir}
pidTmpFile="pidTmpFile.txt"

# ===================================================================
function my_start() {
  cd ${work_dir}
  key1=""
  key2=""

  save_file="save.txt"

  # 检查文件是否存在
  if [ -e "${save_file}" ]; then
      # 文件存在，执行重命名操作
      mv "$save_file" "${save_file}_1.txt"
      echo "文件已重命名为 ${save_file}_1.txt"
  else
      # 文件不存在，输出提示信息
      echo "文件 $save_file 不存在"
  fi

  # 日盘
  flg_rp=$(date "+%Y-%m-%d 08:50:00")
  # 夜盘
  flg_yp=$(date "+%Y-%m-%d 20:30:00")

  # 根据当前时间，更新配置文件中的日期
  #confStr=`cat ./config_tmp.ini`
  confFile="config.ini"

  # 文件名中的时间>14，日盘，<14，夜盘
  if [[ "$(date "+%H")" > "14" ]] # 14 点后启动为夜盘，14点前启动为日盘
  then
    echo "夜盘"
    #isConfStr=`echo "${confStr}" | sed "s/#df_flag#/${flg_yp}/g"`
    ypStr="target_time_all = ${flg_yp}"
    sed -i "3s/.*/${ypStr}/" ${confFile}

  else
    echo "日盘"
    #isConfStr=`echo "${confStr}" | sed "s/#df_flag#/${flg_rp}/g"`
    rpStr="target_time_all = ${flg_rp}"
    sed -i "3s/.*/${rpStr}/" ${confFile}
  fi

  #echo $isConfStr
  #echo $isConfStr > ./my_config.ini

  echo "====== 更新配置文件完成 ======"

  # 启动前先清空队列
  ipcStr1=$(ipcs -q | grep $key1)
  ipcArr1=($ipcStr1)
  msqid1=${ipcArr1[1]}

  # 队列存在时才需要清空
  if [ -z "$msqid1" ]; then # 变量为空，则表示队列不存在
      echo "Message queue with key ${key1} not found."
      #exit 1
  else
      # 清空消息队列
      while true; do
        # 删除队列
        #ipcrm -q 3
        msg1=$(ipcrm -q $msqid1 2>/dev/null) # Q=按key 删除，q=按ID 删除
        if [ $? -ne 0 ]; then
          break
        fi
        echo "清空队列失败，继续尝试"
      done
      echo "Message queue ${key1}) is now empty."
  fi

  # --------------------------
  # 启动前先清空队列
  ipcStr2=$(ipcs -q | grep $key2)
  ipcArr2=($ipcStr2)
  msqid2=${ipcArr2[1]}

  if [ -z "$msqid2" ]; then
      echo "Message queue with key ${key2} not found."
      #exit 1
  else
      # 清空消息队列
      while true; do
        # 删除队列
        #ipcrm -q 3
        msg2=$(ipcrm -q $msqid2 2>/dev/null)
        if [ $? -ne 0 ]; then
          break
        fi
      done
      echo "Message queue ${key2} is now empty."
  fi


  echo "====== 消息队列维护完成 ======"
  echo "当前队列状态："
  ipcs -q


  echo "====== 启动程序 ======"

  touch ${pidTmpFile}
  #nohup ./Network_Traffic_Processing > output.log 2>&1 &
  my_pid=$!
  echo $my_pid > ${pidTmpFile}
  echo "程序启动完成，pid为： $my_pid"
}

function my_stop() {
    cd ${work_dir}
    if test -f "${pidTmpFile}"; then
      for i in `cat ${pidTmpFile}`; do
        echo "kill掉进程 kill -15 $i"
        kill -15 $i
        rm -rf ${pidTmpFile}
        mv ./save.txt ./save_$(date "+%Y%m%d_%H%M%S").txt
        mv ./runingTimeLogger.txt ./runingTimeLogger_$(date "+%Y%m%d_%H%M%S").txt
        cp ./save_$(date "+%Y%m%d_%H%M%S").txt /root/tmpDir/
      done
    fi

    echo "stop-当前队列状态："
    ipcs -q
}

function clean_n_file() {
  local n=$1
  local filePrefix=$2
  local fileDir=$3
  cd ${fileDir}

  cleFileList=$(find ${fileDir} -type f -name "${filePrefix}*" ! -newermt "-${n} days")
  echo "要删除的文件：${cleFileList}"
  for file in $cleFileList; do
    if [ -e "${file}" ];then
      echo "删除旧文件：${file}"
      rm -rf ${file}
    else
      echo "${file} 旧文件不存在"
      continue
    fi
  done
}


# ==========================================================================
# 处理命令行参数
case "$1" in
	start)
	  echo "**************** 脚本于 $(date "+%Y%m%d_%H%M%S") 触发开始指令。****************"
	  my_start
		;;
	stop)
	  echo "**************** 脚本于 $(date "+%Y%m%d_%H%M%S") 触发停止指令。****************"
	  my_stop
	  clean_n_file 20 "runingTimeLogger_" "/home/app/Network_Traffic_Processing/"
	  clean_n_file 30 "save_" "/home/app/Network_Traffic_Processing/"
		;;
	*)
		echo "$program 请选择启动参数 : {start|stop}"
		;;
esac



